<template>
    <el-tooltip
      v-bind="{...defaultProps,...$attrs}"
      :disabled="!canUse"
    >
      <slot slot="content" name="content" />
      <span class="overflow-tooltip">
        <span :ref="refs" :emit="handleShow()">
          <slot name="default" />
        </span>
      </span>
    </el-tooltip>
  </template>
  
  <script>
  /**
   * @group 单个组件的封装 mc-ui
   * 基于el-tooltip扩展:文字没有溢出时禁用,有溢出时启用
   * 功能场景类似el-table-column的文字溢出
   */
  
  import { uniqueId } from 'lodash'
  
  export default {
    props: {
      // 是否禁用,此属性为true时设置disabledByOverFlow无效
      disabled: {
        type: Boolean,
        default: false
      },
      // 气泡是否根据文字是否溢出自动设置disabled,默认开启
      disabledByOverFlow: {
        type: Boolean,
        default: true
      }
    },
    data () {
      return {
        canUse: true
      }
    },
    computed: {
      // tooltip默认顶部出现，content默认是slot的文本
      defaultProps () {
        const src = this.$slots.default && (this.$slots.default[0].data?.domProps?.innerHTML || this.$slots.default[0].text) || ''
        const doc = (new DOMParser()).parseFromString(src, 'text/html')
        return { placement: 'top', content: doc.body.innerText }
      }
    },
    watch: {
      disabled: {
        immediate: true,
        handler (val) {
          this.canUse = !val
        }
      }
    },
    created () {
      this.refs = uniqueId('overflow-tooltip' + new Date().getTime())
    },
    methods: {
      handleShow () {
        if (!this.disabled && this.disabledByOverFlow) {
          this.$nextTick(() => {
            const node = this.$refs[this.refs]
            // 计算是否启用气泡
            this.canUse = node.parentNode?.offsetWidth < node?.offsetWidth
          })
        }
      }
    }
  }
  </script>
  
  <style lang="scss" scoped>
  .overflow-tooltip{
      display: inline-block;
      width: 100%;
      height: 100%;
  }
  </style>
  